package com.ltc.smstimer;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ltc.smstimer.address.ContactListView;
import com.ltc.smstimer.brillent.Brillient;
import com.ltc.smstimer.timer.TimerSendActivity;

public class SmsTimerActivity extends Activity {
	//添加联系人
	//private String tel = null;
	//private String[] telList = null;
	private static final int CONTACT_REQUEST_CODE = 4;
	private static final int CONTACT_REQUEST_BRI = 5;
	
	//是否保存信息
    boolean saveMessageB = true;
    
    //定时
//  private int mYear;
//	private int mMonth;
//	private int mDay;
//	private int mHour;
//	private int mMinute;
	
	Calendar calendar=Calendar.getInstance();
	Intent mainIntent;
	Bundle mainBundle;
	AlarmManager alarmManager;
	
	//短信
	private String address;
	private String messageText;
	//声明控件
	Button addContactBtn;       //添加联系人按钮
	EditText contactPhoneNumEt; //联系人输入框
	
	Button showMenuBtn;     //弹出选项按钮
	Button sendMessageBtn;  //发送短信按钮
	Button sendMessageOntimeBtn; //定时发送短信按钮
	TextView smsWordsTextView;   //短信字数
	EditText messageEidtText;    //短信编辑框
	
	
	//短信列表
	private ListView messageListVIew;
	private List<Map<String, Object>> messageList;

	
	protected void onCreate(Bundle savedInstanceState) {	
		
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.write_message);
		
		//定时
		mainIntent = this.getIntent();
        mainBundle = mainIntent.getExtras();
        
        if(mainBundle!=null){
            String setedtime=mainBundle.getString("time");
        }
		
		//绑定控件
		contactPhoneNumEt = (EditText)findViewById(R.id.write_message_contact_edittext);
		smsWordsTextView = (TextView)findViewById(R.id.zuoxiajiao);
		messageEidtText = (EditText)findViewById(R.id.sendMessage);
		
		//添加联系人按钮
		addContactBtn = (Button)findViewById(R.id.write_message_addcontact);
		addContactBtn.setOnClickListener(new OnClickListener() {
			
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(SmsTimerActivity.this, ContactListView.class);
				Bundle bundle = new Bundle();
				String wNumberStr = contactPhoneNumEt.getText().toString();
				bundle.putString("wNumberStr", wNumberStr);
				intent.putExtras(bundle);
				startActivityForResult(intent, CONTACT_REQUEST_CODE);
				
			}
		});
		
		//添加短信元素按钮
		showMenuBtn = (Button)findViewById(R.id.myButton1);
		showMenuBtn.setOnClickListener(new OnClickListener() {
			
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				//弹出菜单
//				new AlertDialog.Builder(SmsTimerActivity.this)
//				.setTitle("添加")
//				.setItems(R.array.items_irdc_dialog,/*引用String.xml中的array*/
//						new DialogInterface.OnClickListener() {
//							
//							
//							public void onClick(DialogInterface dialog, int which) {
//								// TODO Auto-generated method stub
//								//参数which为对应的列表id，动0开始
////								Toast.makeText(getApplicationContext(), "--------"+which, Toast.LENGTH_LONG).show();
//								
//								//添加精彩短信
//								if(which == 3){
//									Intent intent = new Intent();
//									intent.setClass(SmsTimerActivity.this, Brillient.class);
//									startActivityForResult(intent,CONTACT_REQUEST_BRI);
//								}
//							}
//						}).show();
				Intent intent = new Intent();
				intent.setClass(SmsTimerActivity.this, Brillient.class);
				startActivityForResult(intent,CONTACT_REQUEST_BRI);
			}
		});
		
		
		//即时发信Button
		sendMessageBtn = (Button)findViewById(R.id.send);
		sendMessageBtn.setOnClickListener(new OnClickListener() {
			
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				address = contactPhoneNumEt.getText().toString();
				String[] temp = address.split(",");
				int k = temp.length;
				
				messageText = messageEidtText.getText().toString();
				
				//首先对联系人类表和短信内容进行判断，两者都不为空就发送信息。
				//循环发送实现群发
				if(address.trim().length() != 0 && messageText.trim().length() != 0){
					//发送短信
					Toast.makeText(getApplicationContext(),"--总计发送给"+k+"个联系人",Toast.LENGTH_LONG).show();
					for(int i =0; i < k; ++i ){
						try{
							Toast.makeText(getApplicationContext(),"正在向"+temp[i]+"发送",Toast.LENGTH_LONG).show();
							SmsManager sms = SmsManager.getDefault(); 
							PendingIntent pi = PendingIntent.getBroadcast(SmsTimerActivity.this,0,new Intent(),0);
							//将短信分割
							List<String> texts = sms.divideMessage(messageText);
							for(String text:texts){
								sms.sendTextMessage(temp[i],null,messageText,pi,null);  
							}
							Toast.makeText(getApplicationContext(),"向"+temp[i]+"发送成功",Toast.LENGTH_LONG).show(); 
						}catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
							Toast.makeText(getApplicationContext(),"向发送"+temp[i]+"失败",Toast.LENGTH_LONG).show();
						}
						//将短信保存在发件箱
						if(saveMessageB){
							try{
								ContentValues values = new ContentValues(); 
								values.put("address", temp[i]); 
								values.put("body", messageText); 
								getContentResolver().insert(Uri.parse("content://sms/sent"), values); 
								Toast.makeText(getApplicationContext(),"短信已保存到系统数据库",Toast.LENGTH_LONG).show();
							}catch (Exception e) {
								// TODO: handle exception
								e.printStackTrace();
								Toast.makeText(getApplicationContext(),"短信未保存到系统数据库中",Toast.LENGTH_LONG).show();
							}
						}
						else{
							Toast.makeText(getApplicationContext(),"短信未保存到系统数据库中",Toast.LENGTH_LONG).show();
						}
					}
					
					
				}else{
					Toast.makeText(getApplicationContext(),"联系人或短信内容不能为空",Toast.LENGTH_LONG).show();
				}
			}
		});
		
		
		
		//定时发信Button
		sendMessageOntimeBtn = (Button)findViewById(R.id.sendOnTime);
		sendMessageOntimeBtn.setOnClickListener(new OnClickListener() {
			
			
			public void onClick(View v) {
				//获取联系人与短信内容
		    	address = contactPhoneNumEt.getText().toString();	
				messageText = messageEidtText.getText().toString();
				
				//判断联系人与短信内容是否为空
				if(address.trim().length() != 0 && messageText.trim().length() != 0){
					Intent timerIntent = new Intent();
					timerIntent.setClass(SmsTimerActivity.this, TimerSendActivity.class);
					
					Bundle timerBundle = new Bundle();
					timerBundle.putString("address", address);
					timerBundle.putString("messageText", messageText);
					
					timerIntent.putExtras(timerBundle);
					startActivity(timerIntent);
					
				}else{
					Toast.makeText(getApplicationContext(),"联系人或短信内容不能为空",Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	
	//重写获取页面回传值
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	switch (requestCode) {
    	case CONTACT_REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				String numberStr = null;
				Bundle bundle = data.getExtras();
				if (bundle != null) {
					numberStr = bundle.getString("numberStr");
					
				}
				contactPhoneNumEt.setText(numberStr);
			}
			break;
    	case CONTACT_REQUEST_BRI:
    		if(resultCode == RESULT_OK) {
				String brillient = null;
				Bundle bundle = data.getExtras();
				if (bundle != null) {
					brillient = bundle.getString("sms");
					
				}
				messageEidtText.setText(brillient);
			}
		}
    }
}